package com.wx.controller;

import com.wx.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

//@CrossOrigin
@RestController
@RequestMapping("/upload")
@Slf4j
/* 上传图片控制类 */
public class UploadController {
    @PostMapping("/image")
    private Result uploadimage(@RequestParam(value = "file",required = false) MultipartFile image) throws IOException {
        log.info("文件上传："+image);
        //获取原始文件名
        String originFilename = image.getOriginalFilename();
        //构造唯一文件名
        int index = originFilename.lastIndexOf(".");
        String extname = originFilename.substring(index);
        String newFileName = UUID.randomUUID().toString() + "." + extname;
        //将接受的文件存储在磁盘目录中
        image.transferTo(new File("D:\\Learn\\vue\\book-borrow\\src\\assets\\normal\\"+newFileName));

        return Result.success(newFileName);
    }

    @PostMapping("/avatar")
    private Result uploadavatar(@RequestParam(value = "file",required = false) MultipartFile avatar) throws IOException {
        log.info("头像上传："+avatar);
        //获取原始文件名
        String originFilename = avatar.getOriginalFilename();
        //构造唯一文件名
        int index = originFilename.lastIndexOf(".");
        String extname = originFilename.substring(index);
        String newFileName = UUID.randomUUID().toString() + "." + extname;
        //将接受的文件存储在磁盘目录中
        avatar.transferTo(new File("D:\\Learn\\vue\\book-borrow\\src\\assets\\avatar\\"+newFileName));

        return Result.success(newFileName);
    }

    //删除图片功能
    @GetMapping("/dimage")
    private Result deleteimage(String fileName){
        log.info("文件删除{}",fileName);
        File file = new File("D:\\Learn\\vue\\book-borrow\\src\\assets\\normal\\" + fileName);
        //判断文件存不存在
        if(!file.exists()){
            return Result.error("删除失败");
        }else{
            //判断这是不是一个文件，ps：有可能是文件夹
            if(file.isFile()){
                file.delete();
            }
        }
        return Result.success();
    }

    //删除图片功能
    @GetMapping("/davatar")
    private Result deleteavatar(String fileName){
        log.info("头像删除{}",fileName);
        File file = new File("D:\\Learn\\vue\\book-borrow\\src\\assets\\avatar\\" + fileName);
        //判断文件存不存在
        if(!file.exists()){
            return Result.error("删除失败");
        }else{
            //判断这是不是一个文件，ps：有可能是文件夹
            if(file.isFile()){
                file.delete();
            }
        }
        return Result.success();
    }
}
